package com.nhh.v.service

import java.util.{Calendar, Date}

import com.nhh.v.mapper._
import com.nhh.v.model.NhhwakCoinDetails
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import scala.collection.JavaConverters._


/**
  * Created by chenkaiming on 2018/9/12.
  */
@Service
class ScheduledTaskService(@Autowired val schedulerLockMapper: NhhwakSchedulerLockMapper,
                          @Autowired val configMapper: NhhwakConfigMapper,
                          @Autowired val usersMapper: NhhwakUsersMapper,
                          @Autowired val coinDetailService: NhhwakCoinDetailsSeivice) extends BaseService {

  def genNhhCoins(): Unit = {
    val taskName = "gen_nhh_coins"
    val genNhhCoinsLock = schedulerLockMapper.getLockByTaskname(taskName)

    val cal = Calendar.getInstance
    val now = cal.getTime
    cal.add(Calendar.DAY_OF_MONTH, -1)
    val oneDayBefore: Date = cal.getTime

    if (genNhhCoinsLock.getStatus == 0) {
      try {
        // Step1: 加锁
        schedulerLockMapper.updateLockByTaskname(taskName, 1)
        val per10minNhhcoins = BigDecimal(configMapper.getWakConfig.getPer10minNhhcoins)
        if (per10minNhhcoins > 0) {
          // Step2: 活跃用户当前总算力
          val activeUsers = usersMapper.getActiveUserHashRate(oneDayBefore)
          if (!activeUsers.isEmpty) {
            val totalHashRate = activeUsers.asScala.map(_.getHashRate).reduce(_ + _)
            val nhhCoinDetails = activeUsers.asScala.map { activeUser ⇒
              NhhwakCoinDetails.builder()
                .userId(activeUser.getId)
                .calctime(now)
                .userHashrate(activeUser.getHashRate)
                .totalHashrate(totalHashRate)
                .per10minNhhcoins(per10minNhhcoins.bigDecimal)
                .source("wak")
                .nhhcoins(java.math.BigDecimal.valueOf(activeUser.getHashRate * per10minNhhcoins.toDouble / totalHashRate))
                .build
            }.toList

            // Step3: 发币
            coinDetailService.addCoinDetailsRecordList(nhhCoinDetails)
          }
        }
      } catch {
        case _ ⇒ //Do Nothing
      } finally {
        // Step4: 释放锁
        schedulerLockMapper.updateLockByTaskname(taskName, 0)
      }
    }
  }

}
